package net.xiaoxiangshop.controller.member;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.inject.Inject;
import com.alibaba.fastjson.JSONObject;
import net.xiaoxiangshop.ErpInterfaceMethod;
import net.xiaoxiangshop.entity.*;
import net.xiaoxiangshop.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.fasterxml.jackson.annotation.JsonView;
import net.xiaoxiangshop.Pageable;
import net.xiaoxiangshop.Results;
import net.xiaoxiangshop.plugin.PaymentPlugin;
import net.xiaoxiangshop.security.CurrentUser;
import net.xiaoxiangshop.util.WebUtils;

/**
 * Controller - 预存款
 * 
 */
@Controller("memberDepositController")
@RequestMapping("/member/member_deposit")
public class MemberDepositController extends BaseController {
	private static final Logger _logger = LoggerFactory.getLogger(MemberDepositController.class);
	/**
	 * ERP中台接口URL
	 */
	@Value("${erp_basic_url}")
	private String erp_basic_url;

	/**
	 * 门店编码
	 */
	@Value("${default_store_no}")
	private String default_store_no;

	/**
	 * 每页记录数
	 */
	private static final int PAGE_SIZE = 10;
	@Inject
	private MemberDepositLogService memberDepositLogService;
	@Inject
	private PluginService pluginService;
	@Inject
	private UserService userService;
	@Inject
	private MemberService memberService;
	@Inject
	private ErpResultService erpResultService;


	/**
	 * 计算支付手续费
	 */
	@PostMapping("/calculate_fee")
	public ResponseEntity<?> calculateFee(String paymentPluginId, BigDecimal rechargeAmount) {
		PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
		if (paymentPlugin == null) {
			return Results.NOT_FOUND;
		}
		if (!paymentPlugin.getIsEnabled() || rechargeAmount == null || rechargeAmount.compareTo(BigDecimal.ZERO) < 0) {
			return Results.UNPROCESSABLE_ENTITY;
		}
		Map<String, Object> data = new HashMap<>();
		data.put("fee", paymentPlugin.calculateFee(rechargeAmount));
		return ResponseEntity.ok(data);
	}

	/**
	 * 检查余额
	 */
	@PostMapping("/check_balance")
	public ResponseEntity<?> checkBalance(@CurrentUser Member currentUser) {
		Map<String, Object> data = new HashMap<>();
		data.put("balance", currentUser.getBalance());
		return ResponseEntity.ok(data);
	}

	/**
	 * 充值
	 */
	@GetMapping("/recharge")
	public String recharge(ModelMap model) {
		List<PaymentPlugin> paymentPlugins = pluginService.getActivePaymentPlugins(WebUtils.getRequest());
		if (!paymentPlugins.isEmpty()) {
			model.addAttribute("defaultPaymentPlugin", paymentPlugins.get(0));
			model.addAttribute("paymentPlugins", paymentPlugins);
		}
		return "member/member_deposit/recharge";
	}

	/**
	 * 充值
	 */
	@GetMapping("/card_recharge")
	public String cardRecharge(ModelMap model) {
		List<PaymentPlugin> paymentPlugins = pluginService.getActivePaymentPlugins(WebUtils.getRequest());
		if (!paymentPlugins.isEmpty()) {
			model.addAttribute("defaultPaymentPlugin", paymentPlugins.get(0));
			model.addAttribute("paymentPlugins", paymentPlugins);
		}
		return "member/member_deposit/card_recharge";
	}

	/**
	 * 充值
	 */
	@GetMapping("/deposit")
	public ResponseEntity<?>  deposit(String cardid,String pwd,ModelMap model) {

		User user = userService.getCurrent();
		Long id = user.getId();
		Member member = memberService.find(id);
		RechargeRequestBean rechargeRequestBean = new RechargeRequestBean();
		rechargeRequestBean.setMethod(ErpInterfaceMethod.CARD_INVEST);
		rechargeRequestBean.setOrgid(default_store_no);
		rechargeRequestBean.setJe("0");

		rechargeRequestBean.setCardid(cardid);
		rechargeRequestBean.setPwd(pwd);
		String msg="充值失败,请您稍后再试.";
		String am="";
		try {
			_logger.info("发送请求信息："+JSONObject.toJSONString(rechargeRequestBean));
			String retV = WebUtils.sendPost(erp_basic_url, JSONObject.toJSONString(rechargeRequestBean));
			JSONObject obj = JSONObject.parseObject(retV);
			_logger.info("获取充值信息："+obj);
			Integer code = obj.getInteger("sub_code");
			if (code == 0) {
				JSONObject obj_data = obj.getJSONObject("data");
				String money = obj_data.getString("czje");
				BigDecimal czje =new BigDecimal(money);

				BigDecimal amount=member.getBalance().add(czje);
				member.setBalance(amount);
				DecimalFormat df1 = new DecimalFormat("0.00");
				am=df1.format(amount);
				memberService.update(member);
				//保存充值记录
				BigDecimal zero = new BigDecimal("0");
				MemberDepositLog log=new MemberDepositLog();
				log.setBalance(amount);
				log.setCredit(czje);
				log.setDebit(zero);
				log.setCardNo(cardid);
				log.setMember(member);
				log.setMemo("充值卡充值"+cardid);
				log.setType(MemberDepositLog.Type.CHARGE_CARD);
				memberDepositLogService.save(log);
				msg="充值成功,请您留意账户变化.";
				_logger.info("充值成功");
			}

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			HashMap hashMap = new HashMap();
			hashMap.put("erpType", "MemberDepositController.deposit");
			hashMap.put("sendTime", simpleDateFormat.format(new Date()));
			hashMap.put("sendText", JSONObject.toJSONString(rechargeRequestBean));
			hashMap.put("type", "4");
			hashMap.put("resultTime", simpleDateFormat.format(new Date()));
			hashMap.put("resultText", retV);
			hashMap.put("resultCode", code);
			hashMap.put("sn",cardid);
			erpResultService.add(hashMap);

		} catch (Exception e) {
			 _logger.info("充值抛出失败异常");
			 e.printStackTrace();
		}
		Map<String, Object> data = new HashMap<>();
		data.put("msg",msg);
		data.put("am",am);
		return ResponseEntity.ok(data);
	}
	/**
	 * 记录
	 */
	@GetMapping("/log")
	public String log(Integer pageNumber, @CurrentUser Member currentUser, ModelMap model) {
		Pageable pageable = new Pageable(pageNumber, PAGE_SIZE);
		model.addAttribute("page",  memberDepositLogService.findPage(currentUser, pageable));
		return "member/member_deposit/log";
	}

	/**
	 * 记录
	 */
	@GetMapping(path = "/log", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView(BaseEntity.BaseView.class)
	public ResponseEntity<?> log(Integer pageNumber, @CurrentUser Member currentUser) {
		Pageable pageable = new Pageable(pageNumber, PAGE_SIZE);
		return ResponseEntity.ok(memberDepositLogService.findPage(currentUser, pageable).getContent());
	}


}